#!/usr/bin/env python3
"""
Installation script for the Python remote control system
Handles dependency installation and system setup
"""

import sys
import subprocess
import platform
import os
from colorama import init, Fore, Style

# Initialize colorama
init()

def print_header():
    """Print installation header"""
    print(f"{Fore.MAGENTA}🐍 Python Remote Control System - Installation{Style.RESET_ALL}")
    print(f"{Fore.MAGENTA}================================================{Style.RESET_ALL}")
    print()

def check_python_version():
    """Check if Python version is compatible"""
    version = sys.version_info
    print(f"{Fore.CYAN}🔍 Checking Python version...{Style.RESET_ALL}")
    
    if version.major < 3 or (version.major == 3 and version.minor < 7):
        print(f"{Fore.RED}❌ Python {version.major}.{version.minor} is not supported{Style.RESET_ALL}")
        print(f"{Fore.YELLOW}   Please upgrade to Python 3.7 or higher{Style.RESET_ALL}")
        return False
    
    print(f"{Fore.GREEN}✅ Python {version.major}.{version.minor}.{version.micro} is supported{Style.RESET_ALL}")
    return True

def check_pip():
    """Check if pip is available"""
    print(f"{Fore.CYAN}🔍 Checking pip...{Style.RESET_ALL}")
    
    try:
        import pip
        print(f"{Fore.GREEN}✅ pip is available{Style.RESET_ALL}")
        return True
    except ImportError:
        print(f"{Fore.RED}❌ pip is not installed{Style.RESET_ALL}")
        print(f"{Fore.YELLOW}   Please install pip first{Style.RESET_ALL}")
        return False

def install_dependencies():
    """Install required dependencies"""
    print(f"{Fore.CYAN}📦 Installing dependencies...{Style.RESET_ALL}")
    
    dependencies = [
        'pynput==1.7.6',
        'pyautogui==0.9.54',
        'colorama==0.4.6',
        'psutil==5.9.5',
        'pyyaml==6.0.1'
    ]
    
    for dep in dependencies:
        try:
            print(f"   Installing {dep}...")
            subprocess.check_call([
                sys.executable, '-m', 'pip', 'install', dep
            ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            print(f"{Fore.GREEN}   ✅ {dep.split('==')[0]} installed{Style.RESET_ALL}")
        except subprocess.CalledProcessError as e:
            print(f"{Fore.RED}   ❌ Failed to install {dep}: {e}{Style.RESET_ALL}")
            return False
    
    print(f"{Fore.GREEN}✅ All dependencies installed successfully{Style.RESET_ALL}")
    return True

def install_from_requirements():
    """Install dependencies from requirements.txt"""
    print(f"{Fore.CYAN}📦 Installing from requirements.txt...{Style.RESET_ALL}")
    
    if not os.path.exists('requirements.txt'):
        print(f"{Fore.YELLOW}⚠️  requirements.txt not found, installing manually{Style.RESET_ALL}")
        return install_dependencies()
    
    try:
        subprocess.check_call([
            sys.executable, '-m', 'pip', 'install', '-r', 'requirements.txt'
        ])
        print(f"{Fore.GREEN}✅ Dependencies installed from requirements.txt{Style.RESET_ALL}")
        return True
    except subprocess.CalledProcessError as e:
        print(f"{Fore.RED}❌ Failed to install from requirements.txt: {e}{Style.RESET_ALL}")
        print(f"{Fore.YELLOW}   Trying manual installation...{Style.RESET_ALL}")
        return install_dependencies()

def check_system_requirements():
    """Check system-specific requirements"""
    system = platform.system().lower()
    print(f"{Fore.CYAN}🔍 Checking system requirements for {system}...{Style.RESET_ALL}")
    
    if system == 'darwin':  # macOS
        print(f"{Fore.YELLOW}⚠️  macOS detected{Style.RESET_ALL}")
        print(f"   You may need to grant accessibility permissions:")
        print(f"   System Preferences > Security & Privacy > Privacy > Accessibility")
        print(f"   Add Terminal or your Python IDE to the list")
        
    elif system == 'linux':
        print(f"{Fore.YELLOW}⚠️  Linux detected{Style.RESET_ALL}")
        print(f"   You may need to install additional packages:")
        print(f"   sudo apt-get install python3-tk python3-dev")
        
    elif system == 'windows':
        print(f"{Fore.GREEN}✅ Windows detected - no additional requirements{Style.RESET_ALL}")
    
    print(f"{Fore.GREEN}✅ System requirements checked{Style.RESET_ALL}")

def test_installation():
    """Test if installation was successful"""
    print(f"{Fore.CYAN}🧪 Testing installation...{Style.RESET_ALL}")
    
    test_imports = [
        ('pynput', 'pynput.mouse'),
        ('pyautogui', 'pyautogui'),
        ('colorama', 'colorama'),
        ('socket', 'socket'),
        ('json', 'json'),
        ('threading', 'threading')
    ]
    
    failed_imports = []
    
    for name, module in test_imports:
        try:
            __import__(module)
            print(f"   ✅ {name}")
        except ImportError as e:
            print(f"   ❌ {name}: {e}")
            failed_imports.append(name)
    
    if failed_imports:
        print(f"{Fore.RED}❌ Some imports failed: {', '.join(failed_imports)}{Style.RESET_ALL}")
        return False
    
    print(f"{Fore.GREEN}✅ All imports successful{Style.RESET_ALL}")
    return True

def show_usage_instructions():
    """Show usage instructions after successful installation"""
    print()
    print(f"{Fore.GREEN}🎉 Installation completed successfully!{Style.RESET_ALL}")
    print()
    print(f"{Fore.CYAN}📋 Quick Start Guide:{Style.RESET_ALL}")
    print(f"{Fore.CYAN}==================={Style.RESET_ALL}")
    print()
    print("1. Test the installation:")
    print(f"   {Fore.YELLOW}python test.py{Style.RESET_ALL}")
    print()
    print("2. On the CONTROLLED computer (where actions will be performed):")
    print(f"   {Fore.YELLOW}python main.py playback{Style.RESET_ALL}")
    print()
    print("3. On the CONTROLLING computer (where you move mouse/type):")
    print(f"   {Fore.YELLOW}python main.py capture{Style.RESET_ALL}")
    print()
    print("For remote control between different computers:")
    print(f"   {Fore.YELLOW}python main.py capture <target-ip> <port>{Style.RESET_ALL}")
    print()
    print("Examples:")
    print(f"   {Fore.GREEN}python main.py capture 192.168.1.100 3001{Style.RESET_ALL}")
    print(f"   {Fore.GREEN}python capture.py localhost 3001{Style.RESET_ALL}")
    print(f"   {Fore.GREEN}python playback.py 3001{Style.RESET_ALL}")
    print()
    print(f"📚 Check README.md for detailed documentation")
    print(f"🆘 Run 'python test.py' if you encounter issues")

def main():
    """Main installation function"""
    print_header()
    
    # Check Python version
    if not check_python_version():
        sys.exit(1)
    
    # Check pip
    if not check_pip():
        sys.exit(1)
    
    # Check system requirements
    check_system_requirements()
    
    # Install dependencies
    if not install_from_requirements():
        print(f"{Fore.RED}❌ Failed to install dependencies{Style.RESET_ALL}")
        sys.exit(1)
    
    # Test installation
    if not test_installation():
        print(f"{Fore.RED}❌ Installation test failed{Style.RESET_ALL}")
        sys.exit(1)
    
    # Show usage instructions
    show_usage_instructions()

if __name__ == '__main__':
    main()